import { getMongoRepository, ObjectID } from 'typeorm';

import { Admins } from '../models/Admin'

class AdminService {

  // 分页查询（废弃）
  find(skipNum: number, limit: number) {
    const adminRepository = getMongoRepository(Admins);
    return adminRepository.find({
      skip: skipNum,
      take: limit
    })
  }

  // 查询全部数据
  findAll() {
    const adminRepository = getMongoRepository(Admins);
    return adminRepository.find()
  }

  // 根据账号查询admin用户
  findOneByAccount(account: string) {
    const adminRepository = getMongoRepository(Admins);
    return adminRepository.findOne({ account })
  }

  // 根据 id 查询 admin 用户
  findById(id: string) {
    const adminRepository = getMongoRepository(Admins);
    return adminRepository.findOne(id)
  }

  // 根据 编号 查询 admin 用户
  findByIdentify(identify: string) {
    const adminRepository = getMongoRepository(Admins);
    return adminRepository.findOne({ identify })
  }

  // 根据 手机号 查询 admin 用户
  findByPhone(phone: string) {
    const adminRepository = getMongoRepository(Admins);
    return adminRepository.findOne({ phone })
  }

  // 保存admin用户
  async save(admin: Admins) {
    const adminRepository = getMongoRepository(Admins);
    return adminRepository.save(admin)
  }

  // 查询admin用户总数量
  async adminCount() {
    const adminRepository = getMongoRepository(Admins);
    const [users, count] = await adminRepository.findAndCount()
    return count
  }

  // 更新头像
  updateAvatar(id: string, avatar: string) {
    const adminRepository = getMongoRepository(Admins);
    return adminRepository.update(id, { avatar })
  }

  // 修改密码
  updatePassWord(id: string, password: string) {
    const adminRepository = getMongoRepository(Admins);
    return adminRepository.update(id, { password })
  }

  // 修改用户状态
  updateState(id: string, state: boolean) {
    const adminRepository = getMongoRepository(Admins);
    return adminRepository.update(id, { state })
  }

  // 修改信息
  updateInfo(id: string, admin: Admins) {
    const adminRepository = getMongoRepository(Admins);
    // delete admin.id
    return adminRepository.update(id, admin)
  }

  // 根据名字模糊查询
  findByNameKey(name: string, skipNum: number, limit: number) {
    const adminRepository = getMongoRepository(Admins);
    return adminRepository.find({
      where: {
        name: { $regex: name }
      },
      skip: skipNum,
      take: limit
    })
  }

  // 根据名字模糊查询，总数量
  async findByNameKeyCount(name: string) {
    const adminRepository = getMongoRepository(Admins);
    const [users, count] = await adminRepository.findAndCount({
      where: {
        name: { $regex: name }
      }
    })
    return count
  }

  // 根据id进行删除
  deleteById(id: string) {
    const adminRepository = getMongoRepository(Admins)
    return adminRepository.delete(id)
  }

  // 创建多个用户
  saveMany(admins: Admins[]){
    const adminRepository = getMongoRepository(Admins);
    return adminRepository.save(admins)
  }
}

export default new AdminService()